﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OurMind.Core.UnionCollection
{
    internal class UnionIndexer<T>
    {

        #region fields

        private List<UnionCollection<T>> _collectionGetterList = new List<UnionCollection<T>>();

        #endregion

        #region methods

        public void Add(UnionCollection<T> collection)
        {
            _collectionGetterList.Add(collection);
        }

        ///<summary>获得集合的集合的全局下标的指定对象。</summary>
        ///<example>
        /// [1,3,5]
        /// [6,8]
        /// index <= 4
        /// result => 8
        ///</example>
        public T GetElementAt(int index)
        {
            var tempIndex = index;
            foreach (var collGetter in _collectionGetterList)
            {
                var count = collGetter.GetCount();
                if (0 <= tempIndex && tempIndex < count)
                {
                    return collGetter.GetElementAt(tempIndex);
                }
                else
                {
                    tempIndex -= count;
                }
            }

            return default(T);
        }

        public int GetCount()
        {
            var sum = 0;
            foreach (var collGetter in _collectionGetterList)
            {
                var count = collGetter.GetCount();
                sum += count;
            }
            return sum;
        }

        #endregion



    }
}
